<template>
  <div>
    <!-- 面包屑部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-row>
        <el-col>
            <el-alert
    title="添加商品信息"
    type="info"
    center
    show-icon>
  </el-alert>
        </el-col>
      </el-row>
      <!-- 步骤条 -->
      <el-row style="margin: 20px 0">
        <el-col>
          <!-- :active="activeName - 0"实现进度条与tabs标签页同步 -->
          <el-steps :space="200" :active="activeName - 0" finish-status="success" align-center>
            <el-step title="基本信息">1</el-step>
            <el-step title="商品参数">2</el-step>
            <el-step title="商品属性">3</el-step>
            <el-step title="商品图片">4</el-step>
            <el-step title="商品内容">5</el-step>
            <el-step title="完成">6</el-step>
          </el-steps>
        </el-col>
      </el-row>
      <el-form :model="addGoodsForm" :rules="addGoodsFormRules" ref="addGoodsFormRef" label-width="100px" class="demo-ruleForm" label-position="top">
      <!-- tabs标签页 -->
       <el-tabs tab-position="left"  v-model="activeName" :before-leave="tabsChange" @tab-click="checkedTab">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model.number="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model.number="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model.number="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
              clearable
              v-model="selectParId"
                :options="goodsCateList"
                :props="addProps"
                @change="parentIdChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in goodsParmsList.many" :key="item.attr_id">
              <!-- 多选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="item2" v-for="(item2, i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in goodsParmsList.only" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action 图片上传地址 -->
            <el-upload
            :headers="headersObj"
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" style="margin-top: 15px" @click="addBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog
    width="50%"
    title="图片预览"
    :visible.sync="imgDialog"
    @close="imgClose">
    <img :src="imgSrc" alt="" style="width: 100%">
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表数据
      goodsCateList: [],
      // 商品参数列表数据
      goodsParmsList: {
        many: [],
        only: []
      },
      // tabs标签页选中页
      activeName: '0',
      // 商品信息数据
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        pics: [],
        goods_introduce: '',
        attrs: [],
        goods_cat: ''
      },
      // 验证规则
      addGoodsFormRules: {
        goods_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },
      // 选中的分类ID数组
      selectParId: [],
      // 级联选择器配置项
      addProps: {
        expandTrigger: 'hover',
        children: 'children',
        label: 'cat_name',
        value: 'cat_id'
      },
      // 图片上传地址
      uploadUrl: 'https://www.liulongbin.top:8888/api/private/v1/upload',
      // 配置图片上传的请求头、
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览窗口的显示隐藏
      imgDialog: false,
      // 预览图片的src
      imgSrc: ''
    }
  },
  created () {
    this.getGoodsCate()
  },
  methods: {
    async getGoodsCate () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取数据列表失败')
      this.goodsCateList = res.data
    },
    // 获取商品参数数据
    async getGoodsParams (type) {
      const { data: res } = await this.$http.get(`categories/${this.selectParId[this.selectParId.length - 1]}/attributes`, { params: { sel: type } })
      if (res.meta.status !== 200) return this.$message.error('获取参数信息失败')

      if (type === 'many') {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? item.attr_vals = [] : item.attr_vals.split(',')
        })
        this.goodsParmsList.many = res.data
      } else {
        this.goodsParmsList.only = res.data
      }
    },
    // 级联选择器的change事件
    parentIdChange () {
      if (this.selectParId.length !== 3) {
        this.selectParId = []
      }
    },
    // 监听tabs的切换
    tabsChange (to, old) {
      if (old === '0') {
        if (this.selectParId.length !== 3) {
          this.$message.error('请选择商品三级分类')
          return false
        }
      }
    //   if (to === '1') {
    //     this.getGoodsParams('many')
    //   }
    //   if (to === '2') {
    //     this.getGoodsParams('only')
    //   }
    },
    checkedTab () {
      console.log(this.activeName)
      if (this.activeName === '1') {
        this.getGoodsParams('many')
      } else if (this.activeName === '2') {
        this.getGoodsParams('only')
      }
    },
    // 监听预览事件
    handlePreview (file) {
      // console.log(file)
      this.imgSrc = file.response.data.url
      this.imgDialog = true
    },
    // 预览对话框的关闭事件
    imgClose () {
      this.imgSrc = ''
      this.imgDialog = false
    },
    // 监听移除图片事件
    handleRemove (file) {
      const ind = this.addGoodsForm.pics.findIndex(item => item.pic === file.response.data.tmp_path)
      this.addGoodsForm.pics.splice(ind, 1)
    },
    // 监听图片上传成功事件
    handleSuccess (response) {
      const imgUrl = { pic: response.data.tmp_path }
      this.addGoodsForm.pics.push(imgUrl)
    },
    // 添加商品的提交事件
    addBtn () {
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入正确的商品信息')

        this.addGoodsForm.goods_cat = this.selectParId.join(',')
        // 处理动态参数
        this.goodsParmsList.many.forEach(x => {
          const obj = {
            attr_id: x.attr_id,
            attr_value: x.attr_vals.join(',')
          }
          this.addGoodsForm.attrs.push(obj)
        })
        // 处理静态属性
        this.goodsParmsList.only.forEach(x => {
          const obj = {
            attr_id: x.attr_id,
            attr_value: x.attr_vals
          }
          this.addGoodsForm.attrs.push(obj)
        })
        console.log(this.addGoodsForm)
        const { data: res } = await this.$http.post('goods', this.addGoodsForm)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        this.$router.go(-1)
      })
    }
  }
}
</script>

<style scoped lang="less">
.el-checkbox {
  margin: 0 10px 0 0!important;
}
</style>
